﻿using System;
using Utilities;
using EntitiesTM;
using Business;

namespace TimeWork
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.Cookies["UName"] != null)
                    TxtEmail.Text = Request.Cookies["UName"].Value;
                if (Request.Cookies["PWD"] != null)
                    TxtPass.Attributes.Add("value", Request.Cookies["PWD"].Value);
                if (Request.Cookies["UName"] != null && Request.Cookies["PWD"] != null)
                    CkRemember.Checked = true;
            }

            if (Session["email"] != null)
            {
                Response.Redirect("Dashboard.aspx");
            }
        }

        protected void BtnLogin_Click(object sender, EventArgs e)
        {
            string email = TxtEmail.Text.ToString();
            string pass = UtiGeneralClass.Md5Encode(TxtPass.Text.ToString());

            EnStaff staff = new EnStaff();
            staff.staffEmail = email;
            staff.staffPassword = pass;

            int[] result = BuStaff.CheckStaffExists(staff);

            switch (result[0])
            {
                case 1:
                    LblNotification.Text = "Email không đúng";
                    break;
                case 2:
                    LblNotification.Text = "Mật khẩu không đúng";
                    break;
                case 0:
                    if (CkRemember.Checked)
                    {
                        Response.Cookies["UName"].Value = email;
                        Response.Cookies["PWD"].Value = TxtPass.Text.ToString();
                        Response.Cookies["UName"].Expires = DateTime.Now.AddMonths(2);
                        Response.Cookies["PWD"].Expires = DateTime.Now.AddMonths(2);
                    }
                    else
                    {
                        Response.Cookies["UName"].Expires = DateTime.Now.AddMonths(-1);
                        Response.Cookies["PWD"].Expires = DateTime.Now.AddMonths(-1);
                    }
                    Session.Timeout = 1440;
                    Session["email"] = email;
                    Session["companyid"] = result[1];
                    //Session["companyid"] = "";
                    Response.Redirect("Dashboard.aspx");
                    break;
                default:
                    LblNotification.Text = "Hãy đăng nhập lại";
                    break;
            }
        }
    }
}